package com.pc_project.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.pc_project.domain.authenticate.AuditAuthenticator;
import com.pc_project.domain.authenticate.UserAuthenticator;
import com.pc_project.utils.RedisCache;
import com.pc_project.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token=request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // security它是一个过滤器链，没有token他会在后面的过滤器查询到没有相关信息抛出异常。
            filterChain.doFilter(request, response);
//            如果没加return，那么security响应回来的时候就会再走一遍过滤器链，那么我们后面的代码就会执行。到时候就会出现错误。
            return;
        }
//        解析token
        String userid;
        try {
            DecodedJWT decodedJWT = TokenUtils.parseJWT(token);
            userid = decodedJWT.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //        从redis获取用户信息
        String redisKey = "login:" + userid;
        //TODO 更改表以后就不做类型验证了，统一UserAuthenticator

        UserAuthenticator authenticator = redisCache.getCacheObject(redisKey);
        //        存入securityContextHolder,同时跳过认证阶段
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(authenticator,null,authenticator.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //最后放行
        filterChain.doFilter(request, response);
    }
}
